package goods_set

import (
	"gitee.com/theegg/go-brick/app/model"
	"gitee.com/theegg/go-brick/app/service/app"
)

// 查询参数
type QueryParams struct {
	PageSize  string `form:"page_size"  binding:"gte=0,lte=100" label:"每页数量"`
	PageIndex string `form:"page_index"  binding:"gte=0,lte=99999" label:"当前页数"`
	CatId     string `form:"cat_id"  binding:"" label:"分类"`
	Title     string `form:"title"  binding:"" label:"名称"`
}

// join数据类型
type GoodsSetJoinMerchantAndCategory struct {
	GoodsSet     `xorm:"extends"`
	MerchantName string
	CatTitle     string
	BrandName    string
}

// 分页获取所有数据
// @param params map 参数
// @return interface{}, error
func GetDataList(params map[string]interface{}) (map[string]interface{}, error) {
	returnData := make(map[string]interface{}, 0)

	queryParams, errBuild := model.BuildAdminQueryParam(params)
	if errBuild != nil {
		return nil, app.NewError(errBuild)
	}

	query := app.Db().Join("LEFT", "merchants", "goods_set.merchant_id = merchants.id").
		Join("LEFT", "goods_category", "goods_set.cat_id = goods_category.id").
		Join("LEFT", "brands", "goods_set.brand_id = brands.id").
		Desc("goods_set.id").Limit(queryParams.Limit, queryParams.Offset)

	// query cat_id
	if _, ok := queryParams.Params["cat_id"]; ok && queryParams.Params["cat_id"] != "" {
		query.Where("goods_set.cat_id = ?", queryParams.Params["cat_id"])
	}

	// query title
	if _, ok := queryParams.Params["title"]; ok && queryParams.Params["title"] != "" {
		query.Where("goods_set.title like  ?", "%"+queryParams.Params["title"].(string)+"%")
	}

	data := make([]GoodsSetJoinMerchantAndCategory, 0)

	// 求总条数
	total, err := query.FindAndCount(&data)
	if err != nil {
		return nil, app.NewError(err)
	}

	returnData["data"] = data
	returnData["total"] = total

	return returnData, nil
}

// 获取单个数据
// @param id int64 数据的id
// @return *GoodsSet, error
func GetItemById(id int64) (*GoodsSet, error) {
	node := new(GoodsSet)
	has, err := app.Engine.Where("id = ?", id).Get(node)

	if err != nil {
		return nil, err
	}

	if !has {
		return nil, app.NewError("对不起, 目标对象不存在")
	}

	return node, nil
}

// @title TableName
// @description join 数据类型必须返回一个主表的　表名
func (GoodsSetJoinMerchantAndCategory) TableName() string {
	return "goods_set"
}
